package com.itcm.skymail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.itcm.common.to.es.SkuEsModel;
import com.itcm.skymail.search.config.SkymailElasticSearchConfig;
import com.itcm.skymail.search.constant.EsConstant;
import com.itcm.skymail.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 描述:
 *
 * @author cm_fighting
 * @create 2020-10-13 4:40 下午
 */
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    private RestHighLevelClient client;

    @Override
    public boolean up(List<SkuEsModel> skuEsModels) throws IOException {
        // 1. 建立索引、映射关系 （在kibana中以完成，创建语句在resource/product-mapping.txt）
        // 2. 保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = client.bulk(bulkRequest, SkymailElasticSearchConfig.COMMON_OPTIONS);
        // es的批量保存 实际上是一条条操作的 结果中也可以分析每条数据保存后的返回信息
        return !bulk.hasFailures();
    }
}
